package com.hp.ssmp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.ssmp.entity.TGoods;
import com.hp.ssmp.entity.TNews;
import com.hp.ssmp.entity.TUser;
import com.hp.ssmp.service.NewsService;
import com.hp.ssmp.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/news")
public class NewsController {

    @Resource
    private NewsService newsService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * @description: 获取新闻公告
     * @param: [type 1：新闻 2：公告 , count 新闻数量]
     * @return: java.util.List<com.hp.entity.Goods>
     **/
    @GetMapping("/getPromotionNews")
    public List<TNews> getPromotionNews(Long type, Long count){
        List<TNews> newsList = null;
        if(redisTemplate.hasKey("PromotionNews_"+type)){
            newsList = (List<TNews>)
                    redisTemplate.opsForValue().get("PromotionNews_"+type);
        }else{
            newsList = newsService.getPromotionNews(type, count);
            redisTemplate.opsForValue().set("PromotionNews_"+type, newsList);
        }
        return newsList;
    }

    /**
     * 分类查询新闻和公告
     * @param currentPage
     * @param pageSize
     * @param newstype
     * @return
     */
    @GetMapping("/newsList")
    public R<Page<TNews>> getNewsPage(Integer currentPage, Integer pageSize,Long newstype) {
        Page<TNews> newPage = newsService.getNewsPage(currentPage, pageSize, newstype);
        return R.success(newPage);
    }

    @GetMapping("/getById")
    public R<TNews> getById(Long newsid) {
        TNews news = newsService.getById(newsid);
        return R.success(news);
    }

    @PostMapping("/add")
    public R add(TNews news) {
        news.setNewstime(new Date());
        boolean result = newsService.save(news);
        if (result) {
            return R.success();
        } else {
            return R.error();
        }
    }

    @GetMapping("/del")
    public R del(Long newsid) {
        boolean result = newsService.removeById(newsid);
        if (result) {
            return R.success();
        } else {
            return R.error();
        }
    }

    /**
     * 修改
     * @param news
     * @return
     */
    @PostMapping("/update")
    public R update(TNews news) {
        news.setNewstime(new Date());
        boolean result = newsService.updateById(news);
        if (result) {
            return R.success();
        } else {
            return R.error();
        }
    }


}
